// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

#include "Rules/ImportRule.h"

namespace CangjieMigrator::Rules {

static std::vector<std::string> StringSplit(const std::string &s, const char split)
{
    std::vector<std::string> result{};
    if (s.empty()) {
        return result;
    }
    auto str = s + split;

    size_t pos = str.find(split);
    while (pos != std::string::npos) {
        auto temp = str.substr(0, pos);
        result.push_back(temp);
        // 去掉已分割的字符串,在剩下的字符串中进行分割
        str = str.substr(pos + 1, str.size());
        pos = str.find(split);
    }

    return result;
}

ImportRule::ImportRule(const TomlConfig &config)
{
    for (auto &e : StringSplit(config["removeImport"], ' ')) {
        remove.emplace_back(e);
    }
    for (auto &e : StringSplit(config["addImport"], ' ')) {
        add.emplace_back(e);
    }
}

bool ImportRule::HasAdd() const
{
    return !add.empty();
}

bool ImportRule::HasRemove() const
{
    return !remove.empty();
}

bool ImportRule::HasElement() const
{
    return HasAdd() || HasRemove();
}

bool ImportRule::CanUpdate() const
{
    return add.size() == 1 && remove.size() == 1;
}

const std::vector<PackageExpression> &ImportRule::GetRemove() const
{
    return remove;
}

const std::vector<PackageExpression> &ImportRule::GetAdd() const
{
    return add;
}

std::string ImportRule::ToString() const
{
    std::string result = "";
    if (!remove.empty()) {
        result += "remove:";
        for (auto &e : remove) {
            result += ' ' + e.ToString();
        }
    }
    if (!add.empty()) {
        if (!remove.empty()) {
            result += '\n';
        }
        result.append("add:");
        for (auto &e : add) {
            result += ' ' + e.ToString();
        }
    }
    return result;
}

} // namespace CangjieMigrator::Rules
